//! RESP (REdis Serialization Protocol) 解析器
//! 
//! 负责解析Redis客户端发送的RESP格式数据，转换为Command对象
//! 同时将CommandResult转换为RESP格式响应

use std::io;
use std::str;
use crate::storage::{Command, CommandResult, CommandFactory};
// use crate::error::Result as StorageResult;  // 已注释：未使用的导入

/// RESP 数据类型
#[derive(Debug, Clone, PartialEq)]
pub enum RespValue {
    /// 简单字符串 (+OK\r\n)
    SimpleString(String),
    /// 错误 (-ERR message\r\n)  
    Error(String),
    /// 整数 (:42\r\n)
    Integer(i64),
    /// 批量字符串 ($6\r\nfoobar\r\n)
    BulkString(Option<String>), // None表示null
    /// 数组 (*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n)
    Array(Vec<RespValue>),
}

/// RESP 解析错误
#[derive(Debug)]
pub enum RespParseError {
    /// 数据不完整，需要更多数据
    Incomplete,
    /// 协议错误
    Protocol(String),
    /// IO错误
    Io(io::Error),
    /// UTF-8编码错误
    Utf8(str::Utf8Error),
}

impl From<io::Error> for RespParseError {
    fn from(err: io::Error) -> Self {
        RespParseError::Io(err)
    }
}

impl From<str::Utf8Error> for RespParseError {
    fn from(err: str::Utf8Error) -> Self {
        RespParseError::Utf8(err)
    }
}

/// RESP 解析器
#[derive(Debug)]
pub struct RespParser {
    /// 内部缓冲区
    buffer: Vec<u8>,
    /// 当前解析位置
    position: usize,
}

impl RespParser {
    /// 创建新的RESP解析器
    pub fn new() -> Self {
        Self {
            buffer: Vec::with_capacity(8192), // 8KB初始容量
            position: 0,
        }
    }

    /// 添加新数据到缓冲区
    pub fn feed_data(&mut self, data: &[u8]) {
        self.buffer.extend_from_slice(data);
    }

    /// 尝试解析一个完整的RESP值
    pub fn parse_value(&mut self) -> Result<Option<RespValue>, RespParseError> {
        if self.position >= self.buffer.len() {
            return Ok(None);
        }

        let start_pos = self.position;
        
        match self.parse_value_internal() {
            Ok(value) => {
                // 解析成功，清理已处理的数据
                self.cleanup_buffer();
                Ok(Some(value))
            }
            Err(RespParseError::Incomplete) => {
                // 数据不完整，回退位置
                self.position = start_pos;
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }

    /// 内部解析实现
    fn parse_value_internal(&mut self) -> Result<RespValue, RespParseError> {
        if self.position >= self.buffer.len() {
            return Err(RespParseError::Incomplete);
        }

        let type_byte = self.buffer[self.position];
        self.position += 1;

        match type_byte {
            b'+' => self.parse_simple_string(),
            b'-' => self.parse_error(),
            b':' => self.parse_integer(),
            b'$' => self.parse_bulk_string(),
            b'*' => self.parse_array(),
            _ => Err(RespParseError::Protocol(format!(
                "Unknown RESP type byte: {}",
                type_byte as char
            ))),
        }
    }

    /// 解析简单字符串 (+OK\r\n)
    fn parse_simple_string(&mut self) -> Result<RespValue, RespParseError> {
        let line = self.read_line()?;
        Ok(RespValue::SimpleString(line))
    }

    /// 解析错误 (-ERR message\r\n)
    fn parse_error(&mut self) -> Result<RespValue, RespParseError> {
        let line = self.read_line()?;
        Ok(RespValue::Error(line))
    }

    /// 解析整数 (:42\r\n)
    fn parse_integer(&mut self) -> Result<RespValue, RespParseError> {
        let line = self.read_line()?;
        let num = line.parse::<i64>()
            .map_err(|_| RespParseError::Protocol(format!("Invalid integer: {line}")))?;
        Ok(RespValue::Integer(num))
    }

    /// 解析批量字符串 ($6\r\nfoobar\r\n 或 $-1\r\n)
    fn parse_bulk_string(&mut self) -> Result<RespValue, RespParseError> {
        let len_line = self.read_line()?;
        let len = len_line.parse::<i64>()
            .map_err(|_| RespParseError::Protocol(format!("Invalid bulk string length: {len_line}")))?;

        if len == -1 {
            // Null bulk string
            return Ok(RespValue::BulkString(None));
        }

        if len < 0 {
            return Err(RespParseError::Protocol(format!("Invalid bulk string length: {len}")));
        }

        let len = len as usize;
        
        // 检查是否有足够的数据
        if self.position + len + 2 > self.buffer.len() {
            return Err(RespParseError::Incomplete);
        }

        let data = &self.buffer[self.position..self.position + len];
        let string = str::from_utf8(data)?.to_string();
        self.position += len;

        // 读取结尾的\r\n
        if self.position + 1 >= self.buffer.len() 
            || self.buffer[self.position] != b'\r' 
            || self.buffer[self.position + 1] != b'\n' {
            return Err(RespParseError::Protocol("Missing CRLF after bulk string".to_string()));
        }
        self.position += 2;

        Ok(RespValue::BulkString(Some(string)))
    }

    /// 解析数组 (*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n)
    fn parse_array(&mut self) -> Result<RespValue, RespParseError> {
        let len_line = self.read_line()?;
        let len = len_line.parse::<i64>()
            .map_err(|_| RespParseError::Protocol(format!("Invalid array length: {len_line}")))?;

        if len == -1 {
            // Null array (treated as empty array for simplicity)
            return Ok(RespValue::Array(Vec::new()));
        }

        if len < 0 {
            return Err(RespParseError::Protocol(format!("Invalid array length: {len}")));
        }

        let mut elements = Vec::with_capacity(len as usize);
        for _ in 0..len {
            let element = self.parse_value_internal()?;
            elements.push(element);
        }

        Ok(RespValue::Array(elements))
    }

    /// 读取一行（直到\r\n）
    fn read_line(&mut self) -> Result<String, RespParseError> {
        let start = self.position;
        
        // 查找\r\n
        while self.position + 1 < self.buffer.len() {
            if self.buffer[self.position] == b'\r' && self.buffer[self.position + 1] == b'\n' {
                let line_data = &self.buffer[start..self.position];
                let line = str::from_utf8(line_data)?.to_string();
                self.position += 2; // 跳过\r\n
                return Ok(line);
            }
            self.position += 1;
        }

        // 没有找到完整的行
        Err(RespParseError::Incomplete)
    }

    /// 清理缓冲区中已处理的数据
    fn cleanup_buffer(&mut self) {
        if self.position > 0 {
            self.buffer.drain(0..self.position);
            self.position = 0;
        }
    }

    /// 将RespValue转换为Command
    pub fn resp_to_command(&self, value: RespValue) -> Result<Box<dyn Command>, RespParseError> {
        match value {
            RespValue::Array(mut elements) => {
                if elements.is_empty() {
                    return Err(RespParseError::Protocol("Empty command array".to_string()));
                }

                // 第一个元素是命令名
                let command_name = match elements.remove(0) {
                    RespValue::BulkString(Some(name)) => name.to_uppercase(),
                    RespValue::SimpleString(name) => name.to_uppercase(),
                    _ => return Err(RespParseError::Protocol("Command name must be a string".to_string())),
                };

                // 剩余元素是参数
                let mut args = Vec::new();
                for element in elements {
                    match element {
                        RespValue::BulkString(Some(arg)) => args.push(arg),
                        RespValue::SimpleString(arg) => args.push(arg),
                        RespValue::Integer(i) => args.push(i.to_string()),
                        RespValue::BulkString(None) => {}, // 忽略null参数
                        _ => return Err(RespParseError::Protocol("Invalid argument type".to_string())),
                    }
                }

                // 使用CommandFactory创建命令
                CommandFactory::create(command_name, args)
                    .map_err(|e| RespParseError::Protocol(format!("Failed to create command: {e}")))
            }
            _ => Err(RespParseError::Protocol("Command must be an array".to_string())),
        }
    }

    /// 将CommandResult转换为RESP格式字节数组
    pub fn command_result_to_resp(&self, result: &CommandResult) -> Vec<u8> {
        match result {
            CommandResult::Ok => b"+OK\r\n".to_vec(),
            CommandResult::String(s) => {
                format!("${}\r\n{}\r\n", s.len(), s).into_bytes()
            }
            CommandResult::Integer(i) => {
                format!(":{i}\r\n").into_bytes()
            }
            CommandResult::Boolean(b) => {
                format!(":{}\r\n", if *b { 1 } else { 0 }).into_bytes()
            }
            CommandResult::Array(arr) => {
                let mut resp = format!("*{}\r\n", arr.len()).into_bytes();
                for item in arr {
                    resp.extend_from_slice(&self.command_result_to_resp(item));
                }
                resp
            }
            CommandResult::Null => b"$-1\r\n".to_vec(),
            CommandResult::Error(msg) => {
                format!("-ERR {msg}\r\n").into_bytes()
            }
        }
    }

    /// 重置解析器状态
    pub fn reset(&mut self) {
        self.buffer.clear();
        self.position = 0;
    }

    /// 获取缓冲区使用情况统计
    pub fn buffer_stats(&self) -> (usize, usize, usize) {
        (self.buffer.len(), self.position, self.buffer.capacity())
    }
}

impl Default for RespParser {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_string() {
        let mut parser = RespParser::new();
        parser.feed_data(b"+OK\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::SimpleString("OK".to_string())));
    }

    #[test]
    fn test_parse_error() {
        let mut parser = RespParser::new();
        parser.feed_data(b"-ERR unknown command\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::Error("ERR unknown command".to_string())));
    }

    #[test]
    fn test_parse_integer() {
        let mut parser = RespParser::new();
        parser.feed_data(b":42\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::Integer(42)));
    }

    #[test]
    fn test_parse_bulk_string() {
        let mut parser = RespParser::new();
        parser.feed_data(b"$6\r\nfoobar\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::BulkString(Some("foobar".to_string()))));
    }

    #[test]
    fn test_parse_null_bulk_string() {
        let mut parser = RespParser::new();
        parser.feed_data(b"$-1\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::BulkString(None)));
    }

    #[test]
    fn test_parse_array() {
        let mut parser = RespParser::new();
        parser.feed_data(b"*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, Some(RespValue::Array(vec![
            RespValue::BulkString(Some("foo".to_string())),
            RespValue::BulkString(Some("bar".to_string())),
        ])));
    }

    #[test]
    fn test_parse_command() {
        let mut parser = RespParser::new();
        parser.feed_data(b"*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n");
        
        let value = parser.parse_value().unwrap().unwrap();
        let command = parser.resp_to_command(value).unwrap();
        
        assert_eq!(command.name(), "SET");
        assert_eq!(command.to_args(), vec!["key".to_string(), "value".to_string()]);
    }

    #[test]
    fn test_incomplete_data() {
        let mut parser = RespParser::new();
        parser.feed_data(b"*2\r\n$3\r\nfoo");
        
        let result = parser.parse_value().unwrap();
        assert_eq!(result, None); // 数据不完整
        
        // 添加剩余数据
        parser.feed_data(b"\r\n$3\r\nbar\r\n");
        let result = parser.parse_value().unwrap();
        assert!(result.is_some()); // 现在应该能解析成功
    }

    #[test]
    fn test_command_result_to_resp() {
        let parser = RespParser::new();
        
        // 测试OK响应
        let resp = parser.command_result_to_resp(&CommandResult::Ok);
        assert_eq!(resp, b"+OK\r\n");
        
        // 测试字符串响应
        let resp = parser.command_result_to_resp(&CommandResult::String("hello".to_string()));
        assert_eq!(resp, b"$5\r\nhello\r\n");
        
        // 测试整数响应
        let resp = parser.command_result_to_resp(&CommandResult::Integer(42));
        assert_eq!(resp, b":42\r\n");
        
        // 测试错误响应
        let resp = parser.command_result_to_resp(&CommandResult::Error("not found".to_string()));
        assert_eq!(resp, b"-ERR not found\r\n");
    }

    #[test]
    fn test_pipeline_commands() {
        let mut parser = RespParser::new();
        // 模拟pipeline：两个GET命令
        parser.feed_data(b"*2\r\n$3\r\nGET\r\n$4\r\nkey1\r\n*2\r\n$3\r\nGET\r\n$4\r\nkey2\r\n");
        
        // 第一个命令
        let value1 = parser.parse_value().unwrap().unwrap();
        let cmd1 = parser.resp_to_command(value1).unwrap();
        assert_eq!(cmd1.name(), "GET");
        
        // 第二个命令
        let value2 = parser.parse_value().unwrap().unwrap();
        let cmd2 = parser.resp_to_command(value2).unwrap();
        assert_eq!(cmd2.name(), "GET");
    }
}